package com.codedancer.campus.common.handler;

import com.codedancer.campus.common.constant.ResponseCode;
import com.codedancer.campus.common.exception.BusinessException;
import com.codedancer.campus.common.response.ApiResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.security.auth.message.AuthException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

;

/**
 * ClassName ExceptionHand Description 定义异常处理方法 Author Lenovo Date 2021/3/14 Version 1.0
 **/
@RestControllerAdvice
@Slf4j
public class ExceptionHand {

    /**
     * validate验证错误处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse<Object> argumentValidException(MethodArgumentNotValidException e) {
        BindingResult br = e.getBindingResult();
        String errorMsg = br.getAllErrors().get(0).getDefaultMessage();
        log.info("参数异常，错误消息：{}", errorMsg);
        return ApiResponse.<Object>builder()
            .code(ResponseCode.PARAM_ERR_CODE)
            .msg(errorMsg.toString())
            .build();
    }

    /**
     * 业务异常错误处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public ApiResponse<Object> codeException(BusinessException e) {
        log.info("业务异常，错误消息：" + e.getMessage());
        return ApiResponse.<Object>builder()
            .code(ResponseCode.BUSINESS_ERR_CODE)
            .msg(e.getMessage())
            .build();
    }


    /**
     * 认证异常错误处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(AuthException.class)
    public ApiResponse<Object> authException(AuthException e) {
        log.warn("认证异常，错误消息：" + e.getMessage());
        return ApiResponse.<Object>builder()
            .code(ResponseCode.AUTH_ERR_CODE)
            .msg(e.getMessage())
            .build();
    }

    /**
     * 其他普通错误处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ApiResponse<Object> otherException(Exception e) {
        e.printStackTrace();
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
            e.printStackTrace(pw);
            log.error("其他异常，错误消息：" + sw.toString());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return ApiResponse.<Object>builder()
            .code(ResponseCode.NORMAL_ERR_CODE)
            .msg(e.getMessage())
            .build();
    }
}
